<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <script th:src="@{/js/jquery.min.js}"></script>
    <th:block th:include="include :: header('新增论文')" />
    <th:block th:include="include :: bootstrap-duallistbox-js" />
    <th:block th:include="include :: bootstrap-suggest-js" />
    <th:block th:include="include :: bootstrap-typeahead-js" />
    <th:block th:include="include :: select2-css"/>
    <th:block th:include="include :: bootstrap-fileinput-css"/>
    <th:block th:include="include :: bootstrap-duallistbox-css" />
    <th:block th:include="include :: datetimepicker-css" />
    <style>
        #suggestionsDropdown {
            display: none; /* 默认隐藏 */
            position: absolute;
            background-color: white;
            border: 1px solid #ccc;
            z-index: 1000;
            height: auto;
            width: auto;
            max-height: 200px;
            overflow-y: auto;
        }
        .row-top-margin {
            margin-top: 20px;
            clear: both;
        }
        .first-author-aligned .first-author-label {
            width: 25% !important;
        }
        .first-author-aligned .first-author-input {
            width: 66.66% !important;
            padding-right: 15px !important; /* 与Bootstrap的col-sm-8保持一致 */
        }
    </style>
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight ibox-content">
        <form class="form-horizontal m" id="form-paper-add" >
            <input type="hidden" id="UserId" th:value="${user}">
            <div class="form-group">
                <label class="col-sm-3 control-label">论文名称：</label>
                <div class="col-sm-8">
                    <div class="input-group-btn">
                        <input name="paperTitle" id="paperTitle" class="form-control" type="text" placeholder="请输入论文名称..." required maxlength="150">
                        <ul class="dropdown-menu dropdown-menu-right" role="menu" id="suggestionsDropdown">
                        </ul>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">论文类型：</label>
                <div class="col-sm-8" >
                    <select  name="paperType" id="paperType" class="form-control" th:with="type=${@dict.getType('sci_paper_type')}" required>
                        <option value="" selected>----请选择----</option>
                        <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"></option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">论文类别：</label>
                <div class="col-sm-8" >

                    <select  name="paperCategory" id="paperCategory" class="form-control" th:with="type=${@dict.getType('sci_paper_k')}" required>
                        <option value="" selected="selected">----请选择----</option>
                        <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"></option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">发表期刊：</label>
                <div class="col-sm-8">
                    <input name="publishedJournal" id="publishedJournal" class="form-control" type="text" required maxlength="50">
                </div>
            </div>
          <div class="form-group">
            <label class="col-sm-3 control-label">发表时间：</label>
            <div class="col-sm-8">
              <div class="input-group date">
                <input autocomplete="off" id="publicationTime" name="publicationTime" class="form-control" placeholder="yyyy-MM-dd" type="text"  required >
                <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
              </div>
            </div>
          </div>
            <div class="col-md-12">
                <div class="form-group">
                    <label class="col-sm-3 control-label">是否与行业联合发表：</label>
                    <div class="col-sm-9">
                        <label class="radio-box">
                            <input name="isIndustryCollaborative" class="form-control" type="radio" value="是" required>是</label>
                        <label class="radio-box">
                            <input name="isIndustryCollaborative" class="form-control" type="radio" value="否">否</label>
                    </div>
                </div>
            </div>

            <div class="col-md-12">
                <div class="form-group">
                    <label class="col-sm-3 control-label">是否与地方联合发表：</label>
                    <div class="col-sm-9">
                        <label class="radio-box">
                            <input name="isLocalCollaborative" class="form-control" type="radio" value="是" required>是</label>
                        <label class="radio-box">
                            <input name="isLocalCollaborative" class="form-control" type="radio" value="否">否</label>
                    </div>
                </div>
            </div>

            <div class="col-md-12">
                <div class="form-group">
                    <label class="col-sm-3 control-label">是否与国际联合发表：</label>
                    <div class="col-sm-9">
                        <label class="radio-box">
                            <input name="isInternationalCollaborative" class="form-control" type="radio" value="是" required>是</label>
                        <label class="radio-box">
                            <input name="isInternationalCollaborative" class="form-control" type="radio" value="否">否</label>
                    </div>
                </div>
            </div>

            <div class="col-md-12">
                <div class="form-group">
                    <label class="col-sm-3 control-label">是否是跨学科论文：</label>
                    <div class="col-sm-9" >
                        <label class="radio-box">
                            <input name="isCrossDiscipline" class="form-control" type="radio" value="是" required>是</label>
                        <label class="radio-box">
                            <input name="isCrossDiscipline" class="form-control" type="radio" value="否">否</label>
                    </div>
                </div>
            </div>
            <div class="col-md-12">
                <div class="form-group">
                    <label class="col-sm-3 control-label">是否是独立作者：</label>
                    <div class="col-sm-9" >
                        <label class="radio-box">
                            <input name="isIndependentauthor" class="form-control" type="radio" value="1" required>是</label>
                        <label class="radio-box">
                            <input name="isIndependentauthor" class="form-control" type="radio" value="0">否</label>
                    </div>
                </div>
            </div>


            <!--            <div class="form-group">-->
<!--                <label class="col-sm-3 control-label">排名：</label>-->
<!--                <div class="col-sm-8">-->
<!--                    <select  name="paperRanking" id="paperRanking" class="form-control m-b" th:with="type=${@dict.getType('sci_paper_qwer')}" required>-->
<!--                        <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"></option>-->
<!--                    </select>-->
<!--                </div>-->
<!--            </div>-->
            <div class="col-xs-6" id="firstAuthorGroup">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required first-author-label">一作：</label>
                    <div class="col-sm-8 first-author-input">
<!--                        <input type="text" id="firstPersonName" class="form-control" name="firstPersonName">-->
<!--                        <input type="hidden" id="firstPersonId" class="form-control" name="firstPersonId" >-->
                        <select name="firstPersonId" class="form-control m-b" id="firstPersonId">
                            <option value="" selected>---其他--</option>                            <!--                        <option th:each="user : ${sysUsers} " th:text="${user.userName}" th:value="${user.userId}"></option>-->
                            <option th:each="user : ${sysUsers}"
                                    th:text="${user.userName}"
                                    th:value="${user.userId}"
                                    th:data-user-id="${user.userId}"></option>
                        </select>
                    </div>
                </div>
            </div>


            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">二作：</label>
                    <div class="col-sm-8">

                        <select name="secondPersonId" class="form-control m-b" id="secondPersonId">
                            <option value="" selected>---其他--</option>                            <!--                        <option th:each="user : ${sysUsers} " th:text="${user.userName}" th:value="${user.userId}"></option>-->
                            <option th:each="user : ${sysUsers}"
                                    th:text="${user.userName}"
                                    th:value="${user.userId}"
                                    th:data-user-id="${user.userId}"></option>
                        </select>
                    </div>
                </div>
            </div>


            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">三作：</label>
                    <div class="col-sm-8">
                        <select name="thirdPersonId" class="form-control m-b" id="thirdPersonId">
                            <option value="" selected>---其他--</option>                            <option th:each="user : ${sysUsers}"
                                    th:text="${user.userName}"
                                    th:value="${user.userId}"
                                    th:data-user-id="${user.userId}"></option>
                        </select>
                    </div>
                </div>
            </div>

            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">四作：</label>
                    <div class="col-sm-8">
                        <select name="fourthPersonId" class="form-control m-b" id="fourthPersonId">
                            <option value="" selected>---其他--</option>                            <option th:each="user : ${sysUsers}"
                                    th:text="${user.userName}"
                                    th:value="${user.userId}"
                                    th:data-user-id="${user.userId}"></option>
                        </select>
                    </div>
                </div>
            </div>


            <div class="form-group">
                <label class="col-sm-3 control-label is-required">通讯作者：</label>
                <div class="col-sm-8">
                    <select name="communicationAuthorId" class="form-control m-b" id="correspondingAuthorId">
                        <option value="">--请选择--</option>
                    </select>
                </div>
            </div>


            <div class="form-group" id="searchWebGroup">
                <label class="col-sm-3 control-label">论文网址：</label>
                <div class="col-sm-8">
                    <input name="search_web" id="search_web" class="form-control" type="text" maxlength="200">
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">论文收录通知：</label>
                <div class="col-sm-8">
                    <input type="hidden" name="text_paper">
                    <div class="file-loading">
                        <input class="form-control file-upload" id="text_paper" name ="file" type="file" >
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">论文原文：</label>
                <div class="col-sm-8">
                    <input type="hidden" name="word_paper">
                    <div class="file-loading">
                        <input class="form-control file-wupload" id="word_paper" name ="file" type="file" >
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">备注：</label>
                <div class="col-sm-8">
                    <input name="remarks" id="remark" class="form-control" type="text" >
                    <input type="hidden" class="form-control" name="remarks" >
                    <div class="summernote" id="remarks"></div>
                </div>
            </div>
        </form>
    </div>
    <div class="row">
        <div class="col-sm-offset-5 col-sm-10">
            <button type="button" class="btn btn-sm btn-primary" onclick="submitHandler()">  </i>保 存</button>&nbsp;
            <button type="button" class="btn btn-sm btn-danger" onclick="closeItem()"> 关 闭 </button>
        </div>
    </div>

    <th:block th:include="include :: footer" />
    <th:block th:include="include :: bootstrap-fileinput-js"/>
    <th:block th:include="include :: datetimepicker-js" />
    <th:block th:include="include :: select2-js"/>
    <th:block th:include="include :: datetimepicker-css" />
    <script th:inline="javascript">
        var prefix = ctx + "system/paper"
        var userId = $("#UserId").val();
        if (userId === "1" ){
            alert("系统管理员添加论文不显示,请退出")
            $(".row").hide()
        }
        $("#form-paper-add").validate({
            focusCleanup: true
        });

        function submitHandler() {
            if ($.validate.form()) {
                // 校验网址
                const searchWeb = $("#search_web").val().trim();
                //if (searchWeb !== "" && !validateUrl(searchWeb)) {
                if (searchWeb !== "" && !validateUrl(searchWeb)) {
                    $.modal.alertError("论文网址格式不正确，请以 http:// 或 https:// 开头");
                    return false;
                }
            }
            if ($.validate.form()) {
                if($("input[name='text_paper']").val()=="")
                    return $.modal.alertError("请上传论文收录通知");
                if($("input[name='word_paper']").val()=="")
                    return $.modal.alertError("请上传论文原文");
                console.log($('#form-paper-add'));
                // 校验作者信息是否重复
                const authorIds = [
                    $("#firstPersonId").val(),
                    $("#secondPersonId").val(),
                    $("#thirdPersonId").val(),
                    $("#fourthPersonId").val()
                ].filter(id => id !== ""); // 过滤掉空值

                // 检查是否有重复的作者ID
                const uniqueAuthors = new Set(authorIds);
                if (authorIds.length !== uniqueAuthors.size) {
                    $.modal.alertError("第一作者到第四作者不能重复");
                    return false;
                }
                $.operate.saveTab(prefix + "/add", $('#form-paper-add').serialize());
            }
        }

        $(".file-upload").fileinput({
            uploadUrl: ctx + 'common/upload/lw',
            initialPreviewAsData: true,
            maxFileCount: 1,
            maxFileSize: 51200,
            autoReplace: true,
            allowedFileExtensions: ["pdf"],
            // 添加提示信息
            allowedFileExtensionsMsg: '只允许上传PDF文件',
            slugCallback: function(filename) {
                if ($("input[name='paperTitle']").val()===""){
                    $(".file-uploada").fileinput('clear');
                    $.modal.alertError("请先输入论文名称");
                    return false;
                }
                // 自定义文件名生成规则
                fileExtension = filename.split('.').pop();
                const year = new Date().getFullYear();
                const newName = year +"-"+ $("input[name='paperTitle']").val() +"-"+ "论文收录通知"+ "." + fileExtension;
                return newName;
            },
        }).on('fileuploaded', function (event, data, previewId, index) {
            $("input[name='" + event.currentTarget.id + "']").val(data.response.url)
            console.log(event);
            console.log(data.response.url)
        }).on('fileremoved', function (event, id, index) {
            $("input[name='" + event.currentTarget.id + "']").val('')
        })

        $(".file-wupload").fileinput({
            uploadUrl: ctx + 'common/upload/lw',
            initialPreviewAsData: true,
            maxFileCount: 1,
        maxFileSize: 51200,
            autoReplace: true,
            allowedFileExtensions: ["docx","doc"],
            // 添加提示信息
            dropZoneTitle: '拖拽Word文件到这里 &hellip;<br>或点击选择按钮<br>支持格式：DOC、DOCX<br>文件数量：1个<br>文件大小：50MB及以下',
            slugCallback: function(filename) {
                if ($("input[name='paperTitle']").val()===""){
                    $(".file-uploada").fileinput('clear');
                    $.modal.alertError("请先输入论文名称");
                    return false;
                }
                // 自定义文件名生成规则
                fileExtension = filename.split('.').pop();
                const year = new Date().getFullYear();
                const newName = year +"-"+ $("input[name='paperTitle']").val() +"-"+ "论文原文"+ "." + fileExtension;
                return newName;
            },
        }).on('fileuploaded', function (event, data, previewId, index) {
            $("input[name='" + event.currentTarget.id + "']").val(data.response.url)
            console.log(event);
            console.log(data.response.url)
        }).on('fileremoved', function (event, id, index) {
            $("input[name='" + event.currentTarget.id + "']").val('')
        })

        $(document).ready(function () {
            $("input[name='publicationTime']").datetimepicker({
                format: "yyyy-mm-dd",
                minView: "month",
                autoclose: true
            });
            // 初始化可搜索下拉框（作者与通讯作者）
            $('#firstPersonId, #secondPersonId, #thirdPersonId, #fourthPersonId, #correspondingAuthorId').select2({
                width: '100%',
                width: '100%',
                placeholder: '\u002D\u002D其他\u002D\u002D',
                allowClear: true
            }).on('change select2:select select2:clear', function(){
                // select2操作后，同步更新通讯作者候选
                updateCorrespondingAuthorOptions();
            });
            // 页面加载时根据论文类别应用一次启禁用规则
            const initialCategory = $('#paperCategory').val();
            if (initialCategory) {
                applyAuthorEnableRule(initialCategory);
            }
            // 初始更新一次通讯作者候选
            updateCorrespondingAuthorOptions();
        });


        // 更新通讯作者下拉框选项
        function updateCorrespondingAuthorOptions() {
            const correspondingAuthorSelect = $('#correspondingAuthorId');
            const selectedAuthors = [];

            // 获取所有选中的作者ID和名称
            $('#firstPersonId, #secondPersonId, #thirdPersonId, #fourthPersonId').each(function() {
                const authorId = $(this).val();
                const authorName = $(this).find('option:selected').text();
                if (authorId && authorId !== '') {
                    selectedAuthors.push({
                        id: authorId,
                        name: authorName
                    });
                }
            });

            // 保存当前选中的通讯作者
            const currentSelected = correspondingAuthorSelect.val();

            // 清空下拉框
            correspondingAuthorSelect.empty();
            correspondingAuthorSelect.append('<option value="">--其他--</option>');

            // 添加选中的作者作为选项
            selectedAuthors.forEach(function(author) {
                correspondingAuthorSelect.append('<option value="' + author.id + '">' + author.name + '</option>');
            });

            // 如果之前选中的通讯作者仍然在选项中，则保持选中状态
            if (currentSelected && selectedAuthors.some(author => author.id === currentSelected)) {
                correspondingAuthorSelect.val(currentSelected);
            }
        }




        $(document).ready(function () {
            // 监听输入框的输入事件
            $('#paperTitle').on('input', function () {
                const query = $(this).val(); // 获取输入框的值
                if (!validateNotAllDigits(query)) {
                    $(this).addClass('is-invalid');
                    //$.modal.alertError("标题不允许为纯数字");
                }
                if (query.length > 150) {
                    $(this).addClass('is-invalid');
                    $.modal.alertError("论文名称长度过长");
                    return;
                }
                // 如果输入为空，则隐藏下拉菜单
                if (query.trim() === '') {
                    console.log("输入为空")
                    $('#suggestionsDropdown').hide();
                    return;
                }

                // 发送 AJAX 请求到后端
                $.ajax({
                    url: prefix+'/queryName/'+query,
                    method: 'POST',
                    data: { q: query }, // 将用户输入作为查询参数
                    success: function (response) {
                        console.log("response:",response)
                        let data = response; // 后端返回的对象
                        if (typeof response === 'string') {
                            try {
                                data = JSON.parse(response);
                            } catch (e) {
                                console.error("Failed to parse response:", e);
                                alert("服务器返回的数据格式错误！");
                                return;
                            }
                        }
                        // if (!Array.isArray(data)) {
                        //     data = [data]; // 将单个对象转换为数组
                        // }
                        console.log(data)
                        console.log("data:",data)
                        // 清空下拉菜单内容
                        $('#suggestionsDropdown').empty();

                        // 如果没有匹配结果，则隐藏下拉菜单
                        if (data.length === 0) {
                            $('#suggestionsDropdown').hide();
                            return;
                        }

                        // 遍历返回的数据，生成下拉菜单项
                        data.forEach(function (item) {
                            console.log("Item data:", item);
                            console.log("isIndustryCollaborative:", item.isIndustryCollaborative);
                            const listItem = $('<ul>')
                                .addClass('dropdown-menu-right')
                                .text(item.paperTitle) // 返回的数据包含 paperTitle 字段

                                .on('click', function () {
                                    // 点击某一项时，将其值填充到输入框中
                                    $('#paperTitle').val(item.paperTitle);
                                    $('#paperCategory').val(item.paperCategory);
                                    $('#publishedJournal').val(item.publishedJournal);

                                    var date = new Date(item.publicationTime);
                                    var year = date.getFullYear();
                                    var month = (date.getMonth() + 1).toString().padStart(2, '0'); // 月份从0开始，所以要加1
                                    var day = date.getDate().toString().padStart(2, '0');
                                    let formattedDate =`${year}-${month}-${day}`;
                                    $('#publicationTime').val(formattedDate);

                                    //处理单选框
                                    if (item.isIndustryCollaborative === '是') {
                                        $('input[name="isIndustryCollaborative"][value="是"]').prop('checked', true).iCheck('update');
                                    } else if (item.isIndustryCollaborative === '否') {
                                        $('input[name="isIndustryCollaborative"][value="否"]').prop('checked', true).iCheck('update');
                                    }
                                    if (item.isLocalCollaborative === '是') {
                                        $('input[name="isLocalCollaborative"][value="是"]').prop('checked', true).iCheck('update');
                                    } else if (item.isLocalCollaborative === '否') {
                                        $('input[name="isLocalCollaborative"][value="否"]').prop('checked', true).iCheck('update');
                                    }
                                    if (item.isInternationalCollaborative === '是') {
                                        $('input[name="isInternationalCollaborative"][value="是"]').prop('checked', true).iCheck('update');
                                    } else if (item.isInternationalCollaborative === '否') {
                                        $('input[name="isInternationalCollaborative"][value="否"]').prop('checked', true).iCheck('update');
                                    }
                                    if (item.isCrossDiscipline === '是') {
                                        $('input[name="isCrossDiscipline"][value="是"]').prop('checked', true).iCheck('update');
                                    } else if (item.isCrossDiscipline === '否') {
                                        $('input[name="isCrossDiscipline"][value="否"]').prop('checked', true).iCheck('update');
                                    }

                                    $('#paperRanking').val(item.paperRanking);
                                    $('#search_web').val(item.search_web);
                                    $('#remark').val(item.remarks);
                                    $('#suggestionsDropdown').hide(); // 隐藏下拉菜单
                                });
                            $('#suggestionsDropdown').append(listItem);
                        });

                        // 显示下拉菜单
                        $('#suggestionsDropdown').show();
                    },
                    error: function () {
                        alert('请求失败，请稍后再试！');
                    }
                });
            });

            // 点击页面其他地方时，隐藏下拉菜单
            $(document).on('click', function (e) {
                if (!$(e.target).closest('#paperTitle, #suggestionsDropdown').length) {
                    $('#suggestionsDropdown').hide();
                }
            });
        });


        // 监听1-4作的选择变化
        $('#firstPersonId, #secondPersonId, #thirdPersonId, #fourthPersonId').on('change', function() {
            updateCorrespondingAuthorOptions();
        });
        // 监听是否独立作者变化
        $('input[name="isIndependentauthor"]').on('change', function () {
            handleIndependentAuthor($(this).val());
        });

        // 监听论文类别变化，动态启禁用作者下拉框
        $('select[name="paperCategory"]').on('change', function () {
            applyAuthorEnableRule($(this).val());
        });

        function handleIndependentAuthor(value) {
            if (value === "1") {
                // 是独立作者：清除二三四作者和通讯作者，隐藏相应控件
                $('#secondPersonId, #thirdPersonId, #fourthPersonId, #correspondingAuthorId').val('').trigger('change');
                $('.form-group:has(#secondPersonId), .form-group:has(#thirdPersonId), .form-group:has(#fourthPersonId), .form-group:has(#correspondingAuthorId)').hide();
                
                // 调整一作布局使其与其他控件对齐
                $('#firstAuthorGroup').removeClass('col-xs-6').addClass('first-author-full-width');
                $('#firstAuthorGroup .form-group').addClass('first-author-aligned');
                
                // 移动论文网址到下一行显示
                $('#searchWebGroup').addClass('row-top-margin');
            } else {
                // 不是独立作者：显示所有作者控件，恢复布局
                $('.form-group:has(#secondPersonId), .form-group:has(#thirdPersonId), .form-group:has(#fourthPersonId), .form-group:has(#correspondingAuthorId)').show();
                
                // 恢复一作原始布局
                $('#firstAuthorGroup').removeClass('first-author-full-width').addClass('col-xs-6');
                $('#firstAuthorGroup .form-group').removeClass('first-author-aligned');
                
                // 恢复论文网址到原始位置
                $('#searchWebGroup').removeClass('row-top-margin');
            }
            updateCorrespondingAuthorOptions();
        }

        function applyAuthorEnableRule(inputValue){
            // 如果选择的是独立作者，优先应用独立作者逻辑
            const isIndependent = $('input[name="isIndependentauthor"]:checked').val();
            if (isIndependent === "1") {
                handleIndependentAuthor("1");
                return;
            }
            
            // 10,11,12: 只允许1-2作者
            if(inputValue == "10" || inputValue == "11" || inputValue == "12") {
                $('#secondPersonId').prop('disabled', false);
                $('#thirdPersonId, #fourthPersonId').prop('disabled', true).val('').trigger('change');
            } else if (inputValue == "8" || inputValue == "9"){
                // 8,9: 仅第一作者
                $('#secondPersonId, #thirdPersonId, #fourthPersonId').prop('disabled', true).val('').trigger('change');
            } else {
                // 其他: 全部可选
                $('#secondPersonId, #thirdPersonId, #fourthPersonId').prop('disabled', false);
            }
            // 更新通讯作者选项
            updateCorrespondingAuthorOptions();
        }


        function validateNotAllDigits(paperTitle) {
            const value = paperTitle.trim();
            const regex = /^\d+$/; // 匹配全为数字的字符串

            if (regex.test(value)) {
                return false;
            }
            return true;
        }
        function validateUrl(string) {
            // 确保网址以 http:// 或 https:// 开头
            if (!string.startsWith('http://') && !string.startsWith('https://')) {
                return false;
            }

            // 使用正则表达式验证网址格式
            const urlPattern = /^(https?):\/\/([^\s\.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})/;
            return urlPattern.test(string);
        }
        function updateAuthorDropdownOptions() {
            // 构造所有未禁用select及其已选值
            var selects = [
                {id: 'firstPersonId', $el: $('#firstPersonId'), selected: $('#firstPersonId').val()},
                {id: 'secondPersonId', $el: $('#secondPersonId'), selected: $('#secondPersonId').val()},
                {id: 'thirdPersonId', $el: $('#thirdPersonId'), selected: $('#thirdPersonId').val()},
                {id: 'fourthPersonId', $el: $('#fourthPersonId'), selected: $('#fourthPersonId').val()}
            ];
            // 收集所有选中的ID，但跳过userId为-1的"其他"选项（因为userId是字符串，所以用'-1'）
            var selectedIds = selects.filter(s => !s.$el.prop('disabled') && s.selected && s.selected !== '-1').map(s => s.selected);

            selects.forEach(currentSel => {
                // 只刷未禁用的
                if (currentSel.$el.prop('disabled')) return;
                currentSel.$el.find('option').each(function() {
                    var val = $(this).val();
                    if (!val) return; // 保留请选择
                    // 如果该选项被其它未禁用下拉选中则禁用(但自身已选要保留)
                    var isByOtherSelected = selectedIds.includes(val) && currentSel.selected !== val;
                    $(this).prop('disabled', isByOtherSelected);
                });
                // 让select2刷新可选项
                if (currentSel.$el.data('select2')) currentSel.$el.trigger('change.select2');
            });
        }
        // 绑定互斥逻辑
        $('#firstPersonId,#secondPersonId,#thirdPersonId,#fourthPersonId').on('change', function(){
            updateAuthorDropdownOptions();
            updateCorrespondingAuthorOptions(); // 通讯作者仍需联动
        });
        // 论文类别变化后，也需要刷新一次可选
        $('select[name=\"paperCategory\"]').on('change', function(){
            updateAuthorDropdownOptions();
            updateCorrespondingAuthorOptions();
        });
        // 页面首次加载也刷新一次保证同步
        $(document).ready(function(){ updateAuthorDropdownOptions(); });
    </script>
</body>
</html>
